package org.blade.personal.mode.codegen;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Table;

public class BaseEntity {

	
	public String alias;
	public BaseEntity(String alias){
		this.alias = alias;
	}
	
	public BaseEntity(){
		
	}
	
	public String getQuerySql(){
		Table table = this.getClass().getAnnotation(Table.class);
		Field[] fields = this.getClass().getDeclaredFields();
		StringBuilder querySql = new StringBuilder();
		
		querySql.append(" select * from ").append(table.name()).append(this.alias)
		.append(" where 1=1 ");
		for(Field field : fields){
			
			try {
				field.setAccessible(true);
				if(field.get(this) != null){
					Column column = field.getAnnotation(Column.class);
					querySql.append(" and ")
					.append(this.alias).append(".")
					.append(column.name())
					.append(" = ?");
				}
				field.setAccessible(false);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return querySql.toString();
	}
	
	public Object[] getQueryParam(){
		Field[] fields = this.getClass().getDeclaredFields();
		List<Object> params = new ArrayList<Object>();
		for(Field field : fields){
			try {
				field.setAccessible(true);
				if(field.get(this) != null){
					params.add(field.get(this));
				}
				field.setAccessible(false);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return params.toArray();
	}
}
